package com.example.yingjiguanli_demo.utils;

import com.example.yingjiguanli_demo.pojo.ExcelQuestionDTO;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ExcelUtils {

    public static List<ExcelQuestionDTO> parseExcelFile(MultipartFile file) {
        List<ExcelQuestionDTO> questionList = new ArrayList<>();

        try (InputStream is = file.getInputStream();
             Workbook workbook = new XSSFWorkbook(is)) {

            Sheet sheet = workbook.getSheetAt(0); // 假设题目在第一个 sheet
            for (int i = 1; i <= sheet.getLastRowNum(); i++) { // 从第2行开始读
                Row row = sheet.getRow(i);
                if (row == null) continue;

                ExcelQuestionDTO questionDTO = new ExcelQuestionDTO();
                questionDTO.setQuestionText(getCellValueAsString(row.getCell(0)));
                questionDTO.setQuestionType(getCellValueAsString(row.getCell(1)));
                questionDTO.setIsMultipleChoice(getCellValueAsBoolean(row.getCell(2)));
                questionDTO.setCorrectAnswer(getCellValueAsString(row.getCell(3))); // 新增
                questionDTO.setOptionA(getCellValueAsString(row.getCell(4)));
                questionDTO.setOptionB(getCellValueAsString(row.getCell(5)));
                questionDTO.setOptionC(getCellValueAsString(row.getCell(6)));
                questionDTO.setOptionD(getCellValueAsString(row.getCell(7)));

                questionList.add(questionDTO);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return questionList;
    }


    private static String getCellValueAsString(Cell cell) {
        return cell != null ? cell.toString() : "";
    }

    private static Boolean getCellValueAsBoolean(Cell cell) {
        return cell != null && cell.getBooleanCellValue();
    }
}


